<template>
  <div class="user">
    <DFPageList ref="dfPageListRef" :pageOptions="pageOptions">
      <template #tree>
        <div class="left-main">
          <LeftTree ref="leftTreeRef" class="left-class" @reloadTable="leftTreeSelect" />
        </div>
      </template>
    </DFPageList>
  </div>
</template>

<script lang="ts" setup name="Organize">
  import { NSwitch } from 'naive-ui';
  import lang from './lang';
  import { useMixins } from '@/hooks/useMixins';
  import {
    getOrgTreeSelect,
    getOrganizationList,
    updateOrgnization,
    createOrgnization,
    getOrgnization,
    deleteOrgnization,
  } from '@/api/common/organization';
  import { FormItemRule } from 'naive-ui';
  import { checkEmailFn } from '@/utils/formCheck';
  import LeftTree from './leftTree.vue';

  const {
    loadLangFn,
    getPageLangValueFn,
    language,
    dialogWarningFn,
    message,
    t,
    getDictDataListFn,
  } = useMixins();

  loadLangFn(lang);

  const dfPageListRef: any = ref(null);
  const leftTreeRef: any = ref(null);

  const orgCode = ref('');
  const leftTreeSelect = (e) => {
    orgCode.value = e;
    dfPageListRef.value && dfPageListRef.value.reloadTableFn();
  };
  const treeData = ref<DeptTree[]>([]);
  provide('treeData', treeData);
  const orgTypeList = ref([]);
  const getListDept = async (): Promise<void> => {
    const { row } = await getOrgTreeSelect();
    treeData.value = row || [];
    orgTypeList.value = await getDictDataListFn('origin_type', 'crm');
  };
  const setDialogDataFn = (e) => {
    e.status = e.status === 0 ? true : false;
    return e;
  };
  getListDept();
  const afterDialogSubmitFn = (e) => {
    const { code = 100 } = e;
    if (code === 0) getListDept();
  };
  const reloadTableFn = () => {
    if (dfPageListRef.value) {
      dfPageListRef.value.reloadTableFn();
    }
  };
  const handleDeleteFn = (recordRow: Recordable) => {
    const { orgId = '' } = recordRow;
    dialogWarningFn({ content: t('common.tipMsg.deleteSelectedMsg') }, async () => {
      const { message: msg = '' }: any = await deleteOrgnization({
        id: orgId,
      });

      reloadTableFn();
      getListDept();
      message.success(msg);
    });
  };

  const setDialogSubmitDataFn = (data = {}, _type) => {
    let obj = {};

    if (data) {
      obj = data;
      obj['status'] = obj['status'] ? 0 : 1;
      obj['parentOrgId'] = 1000;
      obj['hierarchy'] = 1;
      obj['orgCodeFrontDisplay'] = obj['orgCode'];
    }

    return obj;
  };
  const beforeResetFn = () => {
    leftTreeRef.value && leftTreeRef.value?.setValue('');
  };
  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          component: 'NInput',
          label: 'orgCodeFrontDisplay',
        },
        {
          component: 'NInput',
          label: 'orgName',
        },
        {
          component: 'NSelect',
          label: 'orgType',
          options: orgTypeList,
        },
      ],
      beforeResetFn,
    },
    table: {
      rowKey: 'orgId',
      columns: [
        {
          label: 'orgCode',
          key: 'orgCodeFrontDisplay',
        },
        {
          label: 'orgName',
        },
        {
          label: 'orgType',
          key: 'orgTypeName',
        },
        {
          width: 100,
          label: 'status',
          common: true,
          render(row) {
            const { orgName = '' } = row;

            const cancelFn = () => {
              row.statusLoading = false;
            };

            return h(NSwitch, {
              value: row.status === 0,
              loading: !!row.statusLoading,
              'on-update:value': async (value) => {
                row.statusLoading = true;

                const text = getPageLangValueFn(`table.${value ? 'enable' : 'disable'}`);

                dialogWarningFn(
                  {
                    content: `${t('common.tipMsg.primary')}${
                      language.value === 'zh' ? text : ' ' + text + ' '
                    }"${orgName}"?`,
                  },
                  async () => {
                    try {
                      await updateOrgnization({
                        ...row,
                        status: value ? 0 : 1,
                      }).then((_) => {
                        dfPageListRef.value?.reloadTableFn();
                      });
                    } catch (e) {
                      console.log(e);
                    }

                    row.statusLoading = false;
                  },
                  cancelFn,
                  {
                    onNegativeClick: cancelFn,
                    onClose: cancelFn,
                    onMaskClick: cancelFn,
                  }
                );
              },
            });
          },
        },
        {
          label: 'principals',
        },
        {
          label: 'email',
        },
        {
          label: 'phoneNumber',
        },
        {
          label: 'orgIden',
        },
      ],
      action: {
        columns: [
          {
            label: 'edit',
          },
          {
            label: 'delete',
            isArray: false,
            click: (row) => {
              handleDeleteFn(row);
            },
          },
        ],
      },
      operaColumn: [
        {
          label: 'add',
        },
      ],
      requestFn: getOrganizationList,
      reloadTableFn,
      beforeSlotName: 'tree',
      setRequestDataFn: (e) => {
        console.log(e, 3333333333);
        const { entity } = e;
        e.entity = {
          ...entity,
          orgCode: orgCode.value,
        };
        return {
          ...e,
        };
      },
    },
    modalFormDialog: {
      formSchemas: [
        {
          label: 'parentOrgName',
          editDialogDisabled: true,
          required: false,
          maxlength: 30,
          defaultValue: '东方精工',
          componentProps: {
            disabled: true,
          },
          giProps: { span: 2 },
        },
        {
          label: 'orgCode',
          required: true,
          maxlength: 30,
          componentProps: {
            'input-props': { autocomplete: `new-password` },
          },
        },
        {
          prop: 'orgType',
          component: 'NSelect',
          required: true,
          label: 'orgType',
          componentProps: {
            options: orgTypeList,
          },
        },
        {
          label: 'orgName',
          required: true,
          maxlength: 30,
          componentProps: {
            'input-props': { autocomplete: `new-password` },
          },
        },
        {
          label: 'principals',
          required: false,
          maxlength: 30,
          componentProps: {
            'input-props': { autocomplete: `new-password` },
          },
        },
        {
          label: 'phoneNumber',
          required: false,
          maxlength: 30,
          componentProps: {
            'input-props': { autocomplete: `new-password` },
          },
        },
        {
          label: 'email',
          common: true,
          maxlength: 50,
          rules: [
            {
              required: false,
              validator(_rule: FormItemRule, value: string) {
                return checkEmailFn(value, false);
              },
              trigger: ['blur'],
            },
          ],
        },
        {
          label: 'orgIden',
          required: false,
          maxlength: 30,
          componentProps: {
            'input-props': { autocomplete: `new-password` },
          },
        },
        {
          component: 'NSwitch',
          label: 'status',
          common: true,
          defaultValue: true,
        },
      ],
      cols: 2,
      getDataFn: getOrgnization,
      addDataFn: createOrgnization,
      updateDataFn: updateOrgnization,
      setDialogSubmitDataFn,
      afterDialogSubmitFn,
      getDataRowKey: 'orgId',
      getDataKey: 'id',
      setDialogDataFn,
    },
  };
</script>

<style lang="less" scoped>
  :deep(.df-page-list-table) {
    width: calc(100% - 250px) !important;
  }
  .user {
    .left-main {
      width: 240px;
      height: calc(100vh - 290px);
      background-color: #fff;
      margin-right: 10px;
    }
  }
</style>
